package org.soenea.doitall.domain.model.person.mapper;

import java.sql.SQLException;

import org.dsrg.soenea.domain.MapperException;
import org.dsrg.soenea.domain.mapper.LostUpdateException;
import org.soenea.doitall.domain.model.person.Person;
import org.soenea.doitall.domain.model.person.data.PersonTDG;

public class PersonOutputMapper {

	public static void delete(Person p) throws MapperException {
		try {
			final int count = PersonTDG.delete(p.getId(), p.getVersion());
			throwLostUpdateOnCountOfZero(p, count);
		} catch (final SQLException e) {
			throw new MapperException(e);
		}
	}

	public static void insert(Person d) throws MapperException {
		try {
			PersonTDG.insert(d.getId(), d.getVersion(),d.getUserName(), d.getFirstName(),
					d.getLastName(), d.getPassword(), d.getGroupNum());
		} catch (final SQLException e) {
			throw new MapperException(e);
		}
	}

	private static void throwLostUpdateOnCountOfZero(Person p, int count)
			throws LostUpdateException {
		if (count == 0)
			throw new LostUpdateException("Person: id = " + p.getId()
					+ "; version = " + p.getVersion() + " not found");
	}

	public static void update(Person p) throws MapperException {
		try {
			final int count = PersonTDG.update(p.getId(), p.getVersion(),
					p.getGroupNum());
			throwLostUpdateOnCountOfZero(p, count);
			p.setVersion(p.getVersion() + 1);
		} catch (final SQLException e) {
			throw new MapperException(e);
		}
	}
}
